package drds.configuration.db.xml_mapping.dynamic_tag.token_handler;


public class TokenParser {

    private final String openToken;
    private final String closeToken;
    private final TokenHandler tokenHandler;

    public TokenParser(String openToken, String closeToken, TokenHandler tokenHandler) {
        this.openToken = openToken;
        this.closeToken = closeToken;
        this.tokenHandler = tokenHandler;
    }

    public String parse(String sql) {
        if (sql == null || sql.isEmpty()) {
            return "";
        }
        // search open token
        int openTokenIndex = sql.indexOf(openToken);
        if (openTokenIndex == -1) {
            return sql;
        }
        char[] chars = sql.toCharArray();
        final StringBuilder sb = new StringBuilder();
        //
        int offset = 0;

        while (openTokenIndex > -1) {
            // search close token.

            sb.append(chars, offset, openTokenIndex - offset);//openToken之前的内容
            offset = openTokenIndex + openToken.length();
            int closeTokenIndex = sql.indexOf(closeToken, offset);
            if (closeTokenIndex == -1) {
                // close token was not found.
                throw new RuntimeException("close token was not found");
                //测试成功以后需要改为抛出异常信息
            } else {
                StringBuilder expression = new StringBuilder();
                expression.append(chars, offset, closeTokenIndex - offset);//表达式内容
                sb.append(tokenHandler.handleToken(expression.toString()));
                //
                offset = closeTokenIndex + closeToken.length();
                //next token
                openTokenIndex = sql.indexOf(openToken, offset);
            }
        }//end while
        if (offset < chars.length) {
            sb.append(chars, offset, chars.length - offset);
        }
        return sb.toString();
    }
}
